using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RoundController : MonoBehaviour, ISceneController, IUserAction
{
    int round = 0;
    int max_round = 5;
    float timer = 0.5f;
    GameObject disk;
    DiskFactory factory;
    public CCActionManager actionManager;
    public ScoreController scoreController;
    public UserGUI userGUI;
    public GameObject butterfly;
    // Start is called before the first frame update
    void Start()
    {
        userGUI.mode = 0;
        butterfly = GameObject.Instantiate(Resources.Load("Prefabs/red", typeof(GameObject))) as GameObject;
        butterfly.transform.localScale = new Vector3(40f, 25f, 25f);
        butterfly.transform.position = new Vector3(0f, 0.5f, 0f);
    }

    // Update is called once per frame
    void Update()
    {
        if (userGUI.mode == 0) return;
        else butterfly.SetActive(false);
        GetHit();
        GameOver();
        if (round > max_round) return;
        timer -= Time.deltaTime;
        if (timer <= 0 && actionManager.RemainCount() == 0) {
            // 从工厂中获取10个飞碟并添加动作
            for (int i = 1; i <= 10; i++) {
                disk = factory.GetDisk(round);
                actionManager.MoveDisk(disk);
            }
            round += 1;
            if (round <= max_round) {
                userGUI.round = round;
            }
            timer = 5.0f;
        }
    }

    void Awake() {
        SSDirector director = SSDirector.getInstance();
        director.currentSceneController = this;
        director.currentSceneController.LoadResources();
        gameObject.AddComponent<UserGUI>();
        gameObject.AddComponent<CCActionManager>();
        gameObject.AddComponent<ScoreController>();
        gameObject.AddComponent<DiskFactory>();
        factory = Singleton<DiskFactory>.Instance;
        userGUI = gameObject.GetComponent<UserGUI>();
    }
    public void LoadResources() {}

    public void GameOver() {
        if (round > max_round && actionManager.RemainCount() == 0)
            userGUI.gameMessage = "Game Over!";
    }

    public void GetHit() {
        if (Input.GetButtonDown("Fire1")) {
            Camera ca = Camera.main; // 主摄像机视角
            Ray ray = ca.ScreenPointToRay(Input.mousePosition); // 将屏幕坐标转换为世界空间中的射线
            // 返回ray点击
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit)) {
                Debug.Log("Hit detected: " + hit.transform.name);
                scoreController.Record(hit.transform.gameObject);
                hit.transform.gameObject.SetActive(false);
                Destroy(hit.transform.gameObject);
            }
        }
    }
}
